package com.tan.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tan.common.constants.BlendConstants;
import com.tan.core.auth.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author Tan
 * @description 自动填充handler
 * @date 2025/1/27
 */
@Slf4j
@Component
public class AutoInsertMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, BlendConstants.createTimeField, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, BlendConstants.createUserField, Long.class, currentUserId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, BlendConstants.updateTimeField, LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, BlendConstants.updateUserField, Long.class, currentUserId());
    }


    public Long currentUserId() {
        return AuthUtil.getCurrentUser() != null ? AuthUtil.getCurrentUser().getUserId() : BlendConstants.superManagerId;
    }
}
